package org.jeecg.modules.dongchen.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.dongchen.entity.DcLunbo;
import org.jeecg.modules.dongchen.entity.DcAnli;
import org.jeecg.modules.dongchen.entity.DcHome;
import org.jeecg.modules.dongchen.vo.DcHomePage;
import org.jeecg.modules.dongchen.service.IDcHomeService;
import org.jeecg.modules.dongchen.service.IDcLunboService;
import org.jeecg.modules.dongchen.service.IDcAnliService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 首页
 * @Author: jeecg-boot
 * @Date: 2022-03-01
 * @Version: V1.0
 */
@Api(tags = "首页")
@RestController
@RequestMapping("/dc/dcHome")
@Slf4j
public class DcHomeController {
    @Autowired
    private IDcHomeService dcHomeService;
    @Autowired
    private IDcLunboService dcLunboService;
    @Autowired
    private IDcAnliService dcAnliService;

    /**
     * 分页列表查询
     *
     * @param dcHome
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "首页-分页列表查询")
    @ApiOperation(value = "首页-分页列表查询", notes = "首页-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(DcHome dcHome,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<DcHome> queryWrapper = QueryGenerator.initQueryWrapper(dcHome, req.getParameterMap());
        Page<DcHome> page = new Page<DcHome>(pageNo, pageSize);
        IPage<DcHome> pageList = dcHomeService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "首页-首页数据")
    @ApiOperation(value = "首页-首页数据", notes = "首页数据")
    @GetMapping(value = "/home")
    public Result<?> home() {
        return Result.OK(dcHomeService.onePage());
    }

    /**
     * 添加
     *
     * @param dcHomePage
     * @return
     */
    @AutoLog(value = "首页-添加")
    @ApiOperation(value = "首页-添加", notes = "首页-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody DcHomePage dcHomePage) {
        DcHome dcHome = new DcHome();
        BeanUtils.copyProperties(dcHomePage, dcHome);
        dcHomeService.saveMain(dcHome, dcHomePage.getDcLunboList(), dcHomePage.getDcAnliList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param dcHomePage
     * @return
     */
    @AutoLog(value = "首页-编辑")
    @ApiOperation(value = "首页-编辑", notes = "首页-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody DcHomePage dcHomePage) {
        DcHome dcHome = new DcHome();
        BeanUtils.copyProperties(dcHomePage, dcHome);
        DcHome dcHomeEntity = dcHomeService.getById(dcHome.getId());
        if (dcHomeEntity == null) {
            return Result.error("未找到对应数据");
        }
        dcHomeService.updateMain(dcHome, dcHomePage.getDcLunboList(), dcHomePage.getDcAnliList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "首页-通过id删除")
    @ApiOperation(value = "首页-通过id删除", notes = "首页-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        dcHomeService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "首页-批量删除")
    @ApiOperation(value = "首页-批量删除", notes = "首页-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.dcHomeService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "首页-通过id查询")
    @ApiOperation(value = "首页-通过id查询", notes = "首页-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        DcHome dcHome = dcHomeService.getById(id);
        if (dcHome == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dcHome);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "轮播图通过主表ID查询")
    @ApiOperation(value = "轮播图主表ID查询", notes = "轮播图-通主表ID查询")
    @GetMapping(value = "/queryDcLunboByMainId")
    public Result<?> queryDcLunboListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<DcLunbo> dcLunboList = dcLunboService.selectByMainId(id);
        return Result.OK(dcLunboList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "首页案例通过主表ID查询")
    @ApiOperation(value = "首页案例主表ID查询", notes = "首页案例-通主表ID查询")
    @GetMapping(value = "/queryDcAnliByMainId")
    public Result<?> queryDcAnliListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<DcAnli> dcAnliList = dcAnliService.selectByMainId(id);
        return Result.OK(dcAnliList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param dcHome
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DcHome dcHome) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<DcHome> queryWrapper = QueryGenerator.initQueryWrapper(dcHome, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<DcHome> queryList = dcHomeService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<DcHome> dcHomeList = new ArrayList<DcHome>();
        if (oConvertUtils.isEmpty(selections)) {
            dcHomeList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            dcHomeList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<DcHomePage> pageList = new ArrayList<DcHomePage>();
        for (DcHome main : dcHomeList) {
            DcHomePage vo = new DcHomePage();
            BeanUtils.copyProperties(main, vo);
            List<DcLunbo> dcLunboList = dcLunboService.selectByMainId(main.getId());
            vo.setDcLunboList(dcLunboList);
            List<DcAnli> dcAnliList = dcAnliService.selectByMainId(main.getId());
            vo.setDcAnliList(dcAnliList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "首页列表");
        mv.addObject(NormalExcelConstants.CLASS, DcHomePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("首页数据", "导出人:" + sysUser.getRealname(), "首页"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<DcHomePage> list = ExcelImportUtil.importExcel(file.getInputStream(), DcHomePage.class, params);
                for (DcHomePage page : list) {
                    DcHome po = new DcHome();
                    BeanUtils.copyProperties(page, po);
                    dcHomeService.saveMain(po, page.getDcLunboList(), page.getDcAnliList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
